package com.example.passwordmanager;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.passwordmanager.R;
import com.example.passwordmanager.EncryptionUtils;
import com.example.passwordmanager.PasswordRepository;

import java.util.concurrent.CountedCompleter;


public class PasswordEntryActivity extends AppCompatActivity {
    private PasswordRepository repository;
    private int existingId = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAddPasswordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        repository = new PasswordRepository(getApplication());

        // 检查是否为编辑模式
        if (getIntent().hasExtra("password_id")) {
            existingId = getIntent().getIntExtra("password_id", -1);
            loadPasswordData(existingId);
        }
        // 生成密码按钮
        binding.btnGeneratePassword.setOnClickListener(v -> {
            String password = PasswordGenerator.generate(16);
            binding.etPassword.setText(password);
        });


        // 保存按钮
        binding.btnSave.setOnClickListener(v -> savePassword());
    }

    private void loadPasswordData(int id) {
        repository.getPasswordById(id).observe(this, passwordEntry -> {
            if (passwordEntry != null) {
                binding.etTitle.setText(passwordEntry.title);
                binding.etWebsite.setText(passwordEntry.website);
                binding.etUsername.setText(passwordEntry.username);

                try {
                    String decrypted = EncryptionUtils.decrypt(this, passwordEntry.encryptedPassword);
                    binding.etPassword.setText(decrypted);
                } catch (Exception e) {
                    Toast.makeText(this, R.string.decryption_error, Toast.LENGTH_SHORT).show();
                }

                binding.etNotes.setText(passwordEntry.notes);
                binding.btnSave.setText(R.string.update);
            }
        });
    }

    private void savePassword() {
        String title = binding.etTitle.getText().toString().trim();
        String website = binding.etWebsite.getText().toString().trim();
        String username = binding.etUsername.getText().toString().trim();
        String password = binding.etPassword.getText().toString().trim();
        String notes = binding.etNotes.getText().toString().trim();

        if (title.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, R.string.required_fields, Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            String encryptedPassword = EncryptionUtils.encrypt(this, password);

            PasswordRepository entry;
            if (existingId != -1) {
                // 更新现有条目
                entry = new PasswordRepository(title, website, username, encryptedPassword, notes);
                entry.id = existingId;
                repository.update(entry);
            } else {
                // 创建新条目
                entry = new PasswordRepository(title, website, username, encryptedPassword, notes);
                repository.insert(entry);
            }

            Toast.makeText(this, R.string.saved_successfully, Toast.LENGTH_SHORT).show();
            finish();
        } catch (Exception e) {
            Toast.makeText(this, R.string.encryption_error, Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}